package com.chihuo.resource;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import com.chihuo.bussiness.Category;
import com.chihuo.dao.CategoryDao;

public class CategoryResource {
	UriInfo uriInfo;
	Request request;
	int id;

	public CategoryResource(UriInfo uriInfo, Request request, int id) {
		this.uriInfo = uriInfo;
		this.request = request;
		this.id = id;
	}

	@GET
	@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON,
			MediaType.TEXT_XML })
	public Category getCategory() {
		CategoryDao dao = new CategoryDao();
		Category c = dao.findById(id);
		if (c == null) {
			throw new WebApplicationException(Response.Status.NOT_FOUND);
		}
		
		return c;
		
//		// Response.ResponseBuilder builder = Response.ok(c);
//
//		Set<Recipe> recipes = c.getRecipes();
//		GenericEntity<Set<Recipe>> entity = new GenericEntity<Set<Recipe>>(
//				recipes) {
//		};
//		// Response.ResponseBuilder builder = Response.ok(entity);
//
//		JSONObject object = new JSONObject(c);
//		Response.ResponseBuilder builder = Response.ok(object.toString());
//
//		// RecipeDao rDao = new RecipeDao();
//		// List<Recipe> list = rDao.findByCategory(id);
//		// builder = builder.entity(list);
//
//		return builder.build();
	}


	@PUT
	@Consumes({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
	public void updateCategory(JAXBElement<Category> category) {
		CategoryDao dao = new CategoryDao();
		Category c = dao.findById(id);
		if (c == null) {
			throw new WebApplicationException(Response.Status.NOT_FOUND);
		}

		c.setName(category.getValue().getName());
		c.setDescription(category.getValue().getDescription());
		dao.saveOrUpdate(c);
	}

	@DELETE
	public void deleteCategory() {
		CategoryDao dao = new CategoryDao();
		Category c = dao.findById(id);
		if (c == null) {
			throw new WebApplicationException(Response.Status.NOT_FOUND);
		}
		dao.delete(c);
	}

}
